package com.cpe.web.controller.wechat;

import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;

import java.util.Arrays;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.cpe.service.wechat.WechatService;
import com.google.common.base.Joiner;
import com.google.common.collect.Maps;
import com.sql.data.response.JsonResponse;
import com.wechat.api.WechatAPI;
import com.wechat.data.Cryptor;
import com.wechat.data.WechatEnv;
import com.wechat.data.message.Message;
import com.wechat.data.message.receive.ReceivedMessage;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@RequestMapping("/wechat")
public class WechatController {

	@Resource
	private WechatService wechatService;

	@Resource
	private WechatEnv wechatEnv;

	@Resource
	private WechatAPI wechatAPI;

	/**
	 * 微信接入
	 */
	@RequestMapping(value = "/messages", method = GET)
	public String signatureValidation(Cryptor cryptor, HttpServletResponse response) {
		log.info("crpptor=" + cryptor);
		String timestamp = cryptor.getTimestamp();
		String nonce = cryptor.getNonce();
		String token = wechatEnv.getToken();
		if (StringUtils.isAnyBlank(timestamp, nonce, token)) {
			return "sth is wrong...";
		}
		String[] arr = new String[] { timestamp, nonce, token };
		Arrays.sort(arr);
		String ciphertext = DigestUtils.sha1Hex(Joiner.on("").join(arr).toString());
		if (ciphertext.equals(cryptor.getSignature())) {
			return cryptor.getEchostr();
		}
		return "";
	}

	/**
	 * 消息接收
	 * 
	 * @param text
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/messages", method = POST)
	public Object receiveText(@RequestBody ReceivedMessage receivedMessage) {
		Message replyMsg = wechatService.processMsg(receivedMessage);
		log.info("replyMsg:" + replyMsg);
		if (replyMsg == null) {
			return "";
		}
		return replyMsg;
	}

	/**
	 * 获取JS-SDK签名
	 */
	@RequestMapping(value = "/jssdk/signature", method = GET)
	public JsonResponse getJssdkSignature(@RequestParam String timestamp, @RequestParam String nonceStr,
			@RequestParam String url) {
		Map<String, String> map = Maps.newHashMap();
		map.put("timestamp", timestamp);
		map.put("noncestr", nonceStr);
		map.put("url", url);
		map.put("jsapi_ticket", wechatAPI.getJsapiTicket().getTicket());
		String[] keys = map.keySet().toArray(new String[0]);
		Arrays.sort(keys);
		Map<String, String> linkedMap = Maps.newLinkedHashMap();
		for (String key : keys) {
			linkedMap.put(key, map.get(key));
		}
		String signature = DigestUtils.sha1Hex(Joiner.on("&").withKeyValueSeparator("=").join(linkedMap));
		Map<String, String> result = Maps.newHashMap();
		result.put("signature", signature);
		result.put("appId", wechatEnv.getAppid());
		return JsonResponse.ok(result);
	}

	/**
	 * 获取当前的access_token
	 */
	@RequestMapping(value = "/access_token", method = GET)
	public JsonResponse getAccessToken() {
		return JsonResponse.ok(wechatAPI.getAccessToken().getAccess_token());
	}
}
